import { Component, OnInit, OnDestroy } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { NzMessageService, NzModalService } from 'ng-zorro-antd'
import { STColumn, STData } from '@delon/abc'

import { I18NService } from '@core'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { PageService } from '@shared/services/page.service'
import { StoreFull } from '@shared/interfaces/store'
import { Terminal, ITerminalQueryParams, ITermPagination } from '@shared/interfaces/terminal'
import { TerminalService } from 'app/routes/terminal/terminal.abstract.service'
import { TerminalAlinterService } from 'app/routes/terminal/terminal-alinter.service'
import { ETabScrollStatus } from '@shared/enums'
import { DataService } from '@shared/services/data.service'
import { StatusTextMap } from '@shared/interfaces/common'
import { openDownloadDialog } from 'app/utils/helpers'
import { ModalService } from '@shared/services/modal.service'
import { ACLService } from '@delon/acl'

@Component({
  selector: 'app-store-detail-tab-terminal',
  templateUrl: './tab-terminal.component.html',
  styleUrls: ['../../../../shared/styles/table.less'],
  providers: [{ provide: TerminalService, useClass: TerminalAlinterService }],
})
export class StoreDetailTabTerminalComponent extends ListBaseClass<Terminal, ITerminalQueryParams>
  implements OnInit, OnDestroy {
  ifEdit: boolean
  store: StoreFull
  statusTextMap = StatusTextMap

  size = 5
  params: ITerminalQueryParams

  columns: STColumn[] = []

  constructor(
    public msgSrv: NzMessageService,
    public i18n: I18NService,
    public route: ActivatedRoute,
    public router: Router,
    private dataService: DataService,
    private terminalService: TerminalService,
    private pageService: PageService,
    private modal: NzModalService,
    public aclService: ACLService,
  ) {
    super(msgSrv, i18n, route, router)
  }

  ngOnInit(): void {
    this.initColumns()
    const intStoreCode = this.route.parent.snapshot.params['id']

    this.dataService.storeFull$.value$.subscribe(full => {
      this.store = full
    })

    this.params.intStoreCode = intStoreCode
    this.params.size = this.size
    this.queryTableDataWithParams()
  }

  ngOnDestroy() {
    this.pageService.triggerBaseEdit(false)
  }

  initColumns(): void {
    const canLock = this.aclService.canAbility('api.put.camel.terminal.one.freeze')
    const canUnlock = this.aclService.canAbility('api.put.camel.terminal.one.unfreeze')
    const canDownload = this.aclService.canAbility('api.put.camel.terminals.report')
    const canRefreshCDKey = this.aclService.canAbility('api.put.camel.terminal.one.cdkey')
    this.columns = [
      {
        type: 'link',
        title: '终端编号',
        i18n: 'GENERAL.TERMINAL.CODE',
        index: 'common.termCode',
        fixed: 'left',
        width: '120px',
        className: 'text-center',
        click: this.viewDetail.bind(this),
      },
      {
        title: '状态',
        i18n: 'GENERAL.INFO.STATUS',
        width: '100px',
        className: 'text-center',
        render: 'status',
      },
      {
        title: '激活码',
        i18n: 'BIZ.TERMINAL.REDEEM_CODE',
        index: 'common.cdKey',
        width: '100px',
        className: 'text-center',
        render: 'cdKey',
      },
      {
        title: '备注',
        i18n: 'GENERAL.INFO.REMARK',
        index: 'common.remark',
        width: '200px',
        className: 'text-center',
      },
      {
        title: '创建时间',
        i18n: 'GENERAL.INFO.CREATED_AT',
        width: '160px',
        index: 'createdAt',
        type: 'date',
      },
      {
        title: 'Operation',
        i18n: 'GENERAL.INFO.OPERATION',
        fixed: 'right',
        width: '120px',
        className: 'text-center pl-xs pr-xs',
        buttons: [
          {
            text: '',
            click: this.refreshCDKey.bind(this),
            icon: {
              iconfont: 'icon-refresh-twotone',
              type: 'iconfont',
            },
            iif: () => canRefreshCDKey,
          },
          {
            text: '',
            click: this.export.bind(this),
            icon: {
              iconfont: 'icon-download-twotone',
              type: 'iconfont',
            },
            iif: () => canDownload,
          },
          {
            text: '',
            icon: {
              iconfont: 'icon-lock-twotone',
              type: 'iconfont',
            },
            click: this.freezeDialog.bind(this),
            // 未激活状态可以冻结，解冻后转变为正常状态
            iif: record => canLock && (record.common.status === 'normal' || record.common.status === 'init'),
          },
          {
            text: '',
            icon: {
              iconfont: 'icon-unlock-circle',
              type: 'iconfont',
            },
            click: this.unfreezeDialog.bind(this),
            iif: record => canUnlock && record.common.status === 'freeze',
          },
          // {
          //   text: '收款码',
          //   i18n: 'GENERAL.INFO.COLLECT_QR_CODE',
          //   click: data => this.viewDetail(data as Terminal),
          // },
          // {
          //   text: '导出',
          //   i18n: 'BTN.EXPORT',
          //   click: data => this.export(data as Terminal),
          // },
        ],
      },
    ]

  }

  goAddTerminal() {
    this.router.navigate(['biz/terminals/new'])
  }

  queryTableDataWithParams(): void {
    this.loading = true
    this.terminalService.getList(this.params).subscribe(this.renderList.bind(this))
  }

  renderList(res: ITermPagination): void {
    this.data = res.data
    this.total = res.total
    this.loading = false
    this.pageService.setTabScrollStatus(ETabScrollStatus.Scroll)
  }

  // 刷新激活码
  refreshCDKey(record: STData): void {
    const { termCode, intStoreCode } = record.common
    this.terminalService.refreshCdKey(intStoreCode, termCode).subscribe(newCode => {
      this.st.reload()
      this.msg.success(this.trans('GENERAL.NOTIFICATION.REFRESH_SUCCESS'))
    })
  }
  /** 冻结对话框 */
  freezeDialog(record: Terminal): void {
    const { termCode } = record.common
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.TERMINAL_FREEZE_CONFIRM', { termCode }),
      nzOnOk: () => this.freeze(record),
    })
  }

  /** 解冻对话框 */
  unfreezeDialog(record: Terminal): void {
    const { termCode } = record.common
    this.modal.confirm({
      nzTitle: this.trans('GENERAL.NOTIFICATION.WARNING'),
      nzContent: this.trans('GENERAL.NOTIFICATION.TERMINAL_UNFREEZE_CONFIRM', { termCode }),
      nzOnOk: () => this.unfreeze(record),
    })
  }

  /** 冻结操作 */
  freeze(record: Terminal): void {
    const { intStoreCode, termCode } = record.common
    this.terminalService.freeze(intStoreCode, termCode).subscribe(
      values => {
        this.st.reload()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.FREEZE_SUCCESS'))
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.FREEZE_FAIL'))
      },
    )
  }

  /** 解冻操作 */
  unfreeze(record: Terminal): void {
    const { intStoreCode, termCode } = record.common
    this.terminalService.unfreeze(intStoreCode, termCode).subscribe(
      values => {
        this.st.reload()
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_SUCCESS'))
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.UNFREEZE_FAIL'))
      },
    )
  }

  export(data: Terminal) {
    const { termCode, intStoreCode } = data.common
    let params: ITerminalQueryParams = {
      page: this.params.page,
      size: this.params.size,
    }
    Object.assign(params, this.params)
    params = {
      ...params,
      termCode,
      intStoreCode,
    }
    this.goExport(params)
  }

  viewDetail(data: Terminal) {
    const { termCode, intStoreCode } = data.common
    this.router.navigate([`/biz/terminals/${termCode}/of/${intStoreCode}`])
  }

  private goExport(params: ITerminalQueryParams) {
    this.terminalService.getTerminalReport(params).subscribe(data => {
      const { url } = data
      openDownloadDialog(url, '导出终端')
    })
  }
}
